
package com.moji.controller.web;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.google.gson.Gson;
import com.moji.common.base.ApiResult;
import com.moji.common.utils.HttpUtils;
import com.moji.config.WeChatConfig;
import com.moji.common.utils.WXPayUtil;
import com.moji.entity.MjOrder;
import com.moji.entity.MjOrderDetail;
import com.moji.entity.dto.MjOrderCommon;
import com.moji.entity.dto.MojiMiYaoDto;
import com.moji.entity.vo.MijiMoYaoVo;
import com.moji.entity.vo.MijiMoYaoVo1;
import com.moji.service.MjOrderDetailService;
import com.moji.service.MjOrderService;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.util.TextUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.*;

@RestController
@RequestMapping("/web/wechat")
@Slf4j
@Api(tags = "微信相关接口", value = "微信相关接口")
public class WechatController {

//    @Autowired
//    private UserInfoService userInfoService;

    @Autowired
    private WeChatConfig weChatConfig;

//    @Autowired
//    private AuthenticationManager authenticationManager;


    @Autowired
    private MjOrderService orderService;

    @Autowired
    private MjOrderDetailService mjOrderDetailService;

//    @Autowired
//    private RedissonClient redissonClient;
//
//    @Autowired
//    private StatisticsService statisticsService;
    /**
     * 微信开放平台二维码连接
     */

    private final static String OPEN_QRCODE_URL = "https://open.weixin.qq.com/connect/qrconnect?appid=%s&redirect_uri=%s&response_type=code&scope=snsapi_login&state=%s#wechat_redirect";


    /**
     * 开放平台回调url
     * 注意：test16web.tunnel.qydev.com 域名地址要和在微信端 回调域名配置 地址一直，否则会报回调地址参数错误
     */

    private final static String OPEN_REDIRECT_URL = "http://www.huilvnet.com/callback";


/**
 * 微信审核通过后的appid
 */

    //private final static String OPEN_APPID= "wxc3ff5f932168d8c6";

    /**
     * 拼装微信扫一扫登录url
     */

//    @GetMapping("/login_url")
//    @ResponseBody
//    public ApiResponseT loginUrl() throws UnsupportedEncodingException {
//        try {
//            //官方文档说明需要进行编码
//            String callbackUrl = URLEncoder.encode(weChatConfig.getOpenRedirectUrl(), "GBK");
//
//            //格式化，返回拼接后的url，去调微信的二维码
//            String qrcodeUrl = String.format(weChatConfig.getOpenQrcodeUrl(), weChatConfig.getOpenAppid(), callbackUrl, "pc");
//            return ApiResponseT.builder().success(qrcodeUrl);
//        } catch (UnsupportedEncodingException e) {
//            e.printStackTrace();
//            return ApiResponseT.builder().fail("系统异常");
//        }
//    }
//
//    @GetMapping("/login_url_h5")
//    @ResponseBody
//    public ApiResponseT loginUrlh5() throws UnsupportedEncodingException {
//        try {
//            //官方文档说明需要进行编码
//            String callbackUrl = URLEncoder.encode(weChatConfig.getOpenRedirectUrl(), "GBK");
//
//            //格式化，返回拼接后的url，去调微信的二维码
//            String qrcodeUrl = String.format(weChatConfig.getOpenQrcodeUrl(), weChatConfig.getOpenAppid(), callbackUrl, "mset");
//            return ApiResponseT.builder().success(qrcodeUrl);
//        } catch (UnsupportedEncodingException e) {
//            e.printStackTrace();
//            return ApiResponseT.builder().fail("系统异常");
//        }
//    }
//
//    @GetMapping("/binding_url")
//    @ResponseBody
//    public ApiResponseT bindingUrl(@RequestParam(value = "mobile", required = true) String mobile) throws UnsupportedEncodingException {
//        try {
//            //官方文档说明需要进行编码
//            String callbackUrl = URLEncoder.encode(weChatConfig.getOpenRedirectUrl(), "GBK");
//
//            //格式化，返回拼接后的url，去调微信的二维码
//            String qrcodeUrl = String.format(weChatConfig.getOpenQrcodeUrl(), weChatConfig.getOpenAppid(), callbackUrl, mobile);
//            return ApiResponseT.builder().success(qrcodeUrl);
//        } catch (UnsupportedEncodingException e) {
//            e.printStackTrace();
//            return ApiResponseT.builder().fail("系统异常");
//        }
//    }
//
//    @GetMapping("/doBinding")
//    @ResponseBody
//    public ApiResponseT doBinding(@RequestParam(value = "mobile", required = true) String mobile,
//                                  @RequestParam(value = "code", required = true) String code,
//                                  @RequestParam(value = "openId", required = true) String openId,
//                                  HttpServletRequest request) {
//        try {
//            UserLoginResp response = new UserLoginResp();
//            Object smsCode2 = redissonClient.getBucket("sms-code-".concat(mobile)).get();
//            if (Objects.isNull(smsCode2)) {
//                return ApiResponseT.builder().fail("手机号验证码过期，请重新获取！");
//            }
//
//            if (!Objects.equals(smsCode2.toString(), code)) {
//                return ApiResponseT.builder().fail("手机号验证码错误，请重新获取！");
//            }
//            UserInfo wechatUser = userInfoService.getUserByOpenId(openId);
//            UserInfo user = userInfoService.getUserByPhone(mobile);
//            String password = defaultPassword;
//            if (!Objects.isNull(user)) {
//                user.setWechatNick(wechatUser.getWechatNick());
//                user.setOpenId(wechatUser.getOpenId());
//                userInfoService.updateById(user);
//                userInfoService.removeById(wechatUser);
//                password = MD5Util.convertMD5(user.getPassword());
//            } else {
//                wechatUser.setPhone(mobile);
//                wechatUser.setPassword(new MyPasswordEncoder().encode(defaultPassword));
//                user = wechatUser;
//                response.setDefaultPassword(defaultPassword);
//            }
//            JwtAuthenticatioToken token = SecurityUtils.login(request, user.getPhone(), password, authenticationManager);
//
//            response.setName(user.getName());
//            response.setNick(user.getNick());
//            response.setUserId(user.getUserId().toString());
//            response.setToken(token.getToken());
//            response.setPhotoUrl(user.getPhotoUrl());
//            return ApiResponseT.builder().success(response);
//        } catch (Exception e) {
//            e.printStackTrace();
//            return ApiResponseT.builder().fail("系统异常");
//        }
//    }
//
//    @GetMapping("/unBinding")
//    @ResponseBody
//    public ApiResponseT unBinding(@RequestParam(value = "userId", required = true) Long userId, HttpServletRequest request) {
//        try {
//            UserInfo wechatUser = userInfoService.getUserByUserId(userId);
//            wechatUser.setOpenId("");
//            wechatUser.setWechatNick("");
//            userInfoService.updateById(wechatUser);
//            return ApiResponseT.builder().success("");
//        } catch (Exception e) {
//            e.printStackTrace();
//            return ApiResponseT.builder().fail("系统异常");
//        }
//    }
//
//
//    /**
//     * 微信扫码登录，回调地址
//     *
//     * @param code
//     * @param state
//     * @param response
//     * @throws IOException
//     */
//
//    @GetMapping("/user/callback")
//    public void wechatUserCallback(@RequestParam(value = "code", required = true) String code,
//                                   @RequestParam(value = "state", required = false) String state,
//                                   HttpServletRequest request, HttpServletResponse response) throws IOException {
//
//        log.info("**********************************code={},state={}", code, state);
//        //if (StringUtils.isNotEmpty(state)){
//        if (!state.equals("pc") && !state.equals("mset")) {
//            UserInfo user = userInfoService.bandingWechat(code, state);
//            //response.sendRedirect("http://8.140.124.56/personal/zhanghaoSet?activiteIndex=1");
//            response.sendRedirect(weChatConfig.getBindingRedirectUrl());
//        } else {
//            UserInfo user = userInfoService.saveWeChatUser(code);
//            //if (user != null) {
//            //生成jwt
//            if (StringUtils.isNotEmpty(user.getPhone())) {
//                String password = MD5Util.convertMD5(user.getPassword());
//                JwtAuthenticatioToken token = SecurityUtils.login(request, user.getPhone(), password, authenticationManager);
//                //state 当前用户的页面地址，需要拼接 http://  这样才不会站内跳转
//                log.info("===================================token={}", token.toString());
//                //response.sendRedirect("http://"+state+"?token="+token.getToken()+"?userId="+user.getUserId()+"&photeUrl="+user.getPhotoUrl()+"&nickName="+URLEncoder.encode(user.getNick(),"UTF-8"));
//                //response.sendRedirect("http://" + state + "?token=" + token.getToken() + "?userId=" + user.getUserId());
//                if (state.equals("pc")) {
//                    response.sendRedirect(weChatConfig.getScanBindingRedirectUrl() + "?token=" + token.getToken() + "&userId=" + user.getUserId());
//                } else {
//                    response.sendRedirect(weChatConfig.getScanBindingRedirectUrlH5() + "?token=" + token.getToken() + "&userId=" + user.getUserId());
//                }
//            } else {
//                if (state.equals("pc")) {
//                    response.sendRedirect(weChatConfig.getScanUnBindingRedirectUrl() + "?openId=" + user.getOpenId());
//                } else {
//                    response.sendRedirect(weChatConfig.getScanUnBindingRedirectUrlH5() + "?openId=" + user.getOpenId());
//                }
//            }
//        }
//    }


    /**
     * 微信支付回调
     */

    @RequestMapping("/order/callback")
    public void orderCallback(HttpServletRequest request, HttpServletResponse response) throws Exception {

        InputStream inputStream = request.getInputStream();

        //BufferedReader是包装设计模式，性能更搞
        BufferedReader in = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
        StringBuffer sb = new StringBuffer();
        String line;
        while ((line = in.readLine()) != null) {
            sb.append(line);
        }
        in.close();
        inputStream.close();
        log.info("------------#####################-------------sb={}", sb);
        log.info("------------#####################-------------sb="+sb, sb);
        Map<String, String> callbackMap = WXPayUtil.xmlToMap(sb.toString());
        //System.out.println(callbackMap.toString());

        SortedMap<String, String> sortedMap = WXPayUtil.getSortedMap(callbackMap);

        //判断签名是否正确
        if (WXPayUtil.isCorrectSign(sortedMap, weChatConfig.getKey())) {

            if ("SUCCESS".equals(sortedMap.get("result_code"))) {

                String outTradeNo = sortedMap.get("out_trade_no");

                MjOrder order = orderService.getOne(new LambdaQueryWrapper<MjOrder>().eq(MjOrder::getOrderCode, outTradeNo));

                if (order != null && order.getOrderStatus() == 0) {  //判断逻辑看业务场景
                    log.info("------------#####################-------------1111111", "微信支付成功" + outTradeNo);
                    MjOrder upOrder = new MjOrder();
//                    upOrder.setOpenId(sortedMap.get("openid"));
                    //videoOrder.setOutTradeNo(outTradeNo);
                    upOrder.setUpdateTime(new Date());
                    upOrder.setOrderStatus(1);
                    upOrder.setPayAmount(order.getOrderAmount());
                    upOrder.setPayType("1");
                    String transaction_id = sortedMap.get("transaction_id");
                    upOrder.setSpareString1(transaction_id);
                    upOrder.setPayTime(new Date());
//                    upOrder.setPayType(OrderPayTypeEnum.WECHAT.getCode());
                    boolean flag = orderService.update(upOrder, new LambdaQueryWrapper<MjOrder>().eq(MjOrder::getOrderCode, outTradeNo));

                    if (flag) { //通知微信订单处理成功
                        //获取密钥逻辑------------------------
                        //根据订单号查询订单明细表，然后将订单明细得信息生成密钥
                        List<MjOrderDetail> list = mjOrderDetailService.list(new LambdaQueryWrapper<MjOrderDetail>().eq(MjOrderDetail::getOrderCode, order.getOrderCode()));
                        //循环获取密钥
                        if (list != null && list.size() > 0) {
                            for (int i = 0; i < list.size(); i++) {
                                MjOrderDetail mjOrderDetail = list.get(i);
                                MojiMiYaoDto mojiMiYaoDto = new MojiMiYaoDto();
                                mojiMiYaoDto.setOrderId(mjOrderDetail.getOrderMxCode());
                                mojiMiYaoDto.setRegion(mjOrderDetail.getServiceCityCode());
                                mojiMiYaoDto.setType(mjOrderDetail.getCallWayCode());
                                mojiMiYaoDto.setRate(mjOrderDetail.getCallCountCode());
                                mojiMiYaoDto.setDuration(mjOrderDetail.getServiceTimeCode());
                                //判断支付时间，如果支付时间在生效时间之后，以支付时间为准，如果支付时间在生效时间之前，以生效时间为准
                                SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
                                // 使用format方法转换Date到指定格式的字符串
                                String formattedDate = sdf.format(mjOrderDetail.getEffectTime());
                                mojiMiYaoDto.setValidStartTime(formattedDate);
                                List<String> endpoints = new ArrayList<>();
                                if (!TextUtils.isEmpty(mjOrderDetail.getWeatherTypeCode())) {
                                    String[] split = mjOrderDetail.getWeatherTypeCode().split("/");
                                    for (int j = 0; j < split.length; j++) {
                                        endpoints.add(split[j]);
                                    }
                                } else {
                                    String[] split = mjOrderDetail.getGlobalCityCode().split("/");
                                    for (int j = 0; j < split.length; j++) {
                                        endpoints.add(split[j]);
                                    }
                                }
                                mojiMiYaoDto.setEndpoints(endpoints);
                                // 创建Gson对象
                                Gson gson = new Gson();
                                // 将对象转换为JSON字符串
                                String jsonString = gson.toJson(mojiMiYaoDto);

                                String s = null;
                                try {
                                    s = HttpUtils.sendPostRequest("/tob-data-misc/eshop/access/creation", jsonString);
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }
                                Gson gson1 = new Gson();
                                MijiMoYaoVo1 mijiMoYaoVo1 = gson1.fromJson(s, MijiMoYaoVo1.class);
                                if (mijiMoYaoVo1 != null && mijiMoYaoVo1.getCode() == 200) {
                                    Gson gson2 = new Gson();
                                    MijiMoYaoVo mijiMoYaoVo = gson2.fromJson(s, MijiMoYaoVo.class);
                                    if (mijiMoYaoVo.getData().getAccess() != null && mijiMoYaoVo.getData().getAccess().getOrderId() != null) {
                                        //核对订单号
                                        if (mijiMoYaoVo.getData().getAccess().getOrderId().equals(mjOrderDetail.getOrderMxCode())) {
                                            //将密钥更新到订单明细得springString2中
                                            mjOrderDetail.setSpareString2(mijiMoYaoVo.getData().getAccess().getMdsPassword());
                                            mjOrderDetail.setSpareInt2(mijiMoYaoVo.getData().getAccess().getId());
                                            mjOrderDetail.setUpdateTime(new Date());
                                            mjOrderDetail.setUseStatus(1);
                                            mjOrderDetailService.updateById(mjOrderDetail);
                                        }
                                    }
                                }
                                else{
                                    //获取墨迹密钥失败

                                }


                            }
                        }
                        //结束---------------------------


                        response.setContentType("text/xml");
                        response.getWriter().println("success");
                        return;
                    }
                }
            }
        }
        //都处理失败
        response.setContentType("text/xml");
        response.getWriter().println("fail");

    }


//    @GetMapping("/getWachatSign")
//    @ResponseBody
//    public ApiResponseT getWachatSign() throws UnsupportedEncodingException {
//        try {
//            Map<String, String> resultMap = new HashMap<>();
//            //官方文档说明需要进行编码
//            String accessTokenUrl = String.format(WeChatConfig.getCgiBinAccessTokenUrl(), weChatConfig.getAppId(), weChatConfig.getAppsecret());
//            Map<String, Object> baseMap = HttpUtils.doGet(accessTokenUrl);
//            if (baseMap == null || baseMap.isEmpty()) {
//                return null;
//            }
//            log.info("**********************************baseMap={}", JSON.toJSON(baseMap));
//            String accessToken = (String) baseMap.get("access_token");
//
//            String getTicketUrl = String.format(WeChatConfig.getCgiBinGetTicketUrl(), accessToken);
//            Map<String, Object> baseUserMap = HttpUtils.doGet(getTicketUrl);
//
//            if (baseUserMap == null || baseUserMap.isEmpty()) {
//                return null;
//            }
//            log.info("**********************************baseUserMap={}", JSON.toJSON(baseUserMap));
//            String jsapi_ticket = (String) baseUserMap.get("ticket");
//            SortedMap<String, String> params = new TreeMap<>();
//            String noncestr = UUID.randomUUID().toString();
//            String timestamp = Long.toString(System.currentTimeMillis() / 1000);
//            String url = "http://m.huilvnet.com/";
//            params.put("noncestr", noncestr);
//            params.put("jsapi_ticket", jsapi_ticket);
//            params.put("timestamp", timestamp);
//            params.put("url", url);
//            String string1 = "jsapi_ticket=" + jsapi_ticket +
//                    "&noncestr=" + noncestr +
//                    "&timestamp=" + timestamp +
//                    "&url=" + url;
//            log.info("====================" + string1);
//            String signature = "";
//            try {
//                MessageDigest crypt = MessageDigest.getInstance("SHA-1");
//                crypt.reset();
//                crypt.update(string1.getBytes("UTF-8"));
//                signature = byteToHex(crypt.digest());
//            } catch (NoSuchAlgorithmException e) {
//                e.printStackTrace();
//            } catch (UnsupportedEncodingException e) {
//                e.printStackTrace();
//            }
//            resultMap.put("signature", signature);
//            resultMap.put("noncestr", noncestr);
//            resultMap.put("timestamp", timestamp);
//            return ApiResponseT.builder().success(resultMap);
//        } catch (Exception e) {
//            e.printStackTrace();
//            return ApiResponseT.builder().fail("系统异常");
//        }
//    }
//
//
//    private String createSign(SortedMap<String, String> params) {
//        StringBuilder sb = new StringBuilder();
//        Set<Map.Entry<String, String>> es = params.entrySet();
//        Iterator<Map.Entry<String, String>> it = es.iterator();
//
//        //生成 stringA="appid=wxd930ea5d5a258f4f&body=test&device_info=1000&mch_id=10000100&nonce_str=ibuaiVcKdpRxkhJA";
//        while (it.hasNext()) {
//            Map.Entry<String, String> entry = (Map.Entry<String, String>) it.next();
//            String k = (String) entry.getKey();
//            String v = (String) entry.getValue();
//            if (null != v && !"".equals(v) && !"sign".equals(k) && !"key".equals(k)) {
//                sb.append(k + "=" + v + "&");
//            }
//        }
//        String signature = "";
//        try {
//            String string1 = sb.toString();
//            log.info("====================" + string1);
//            MessageDigest crypt = MessageDigest.getInstance("SHA-1");
//            crypt.reset();
//            crypt.update(string1.getBytes("UTF-8"));
//            signature = byteToHex(crypt.digest());
//        } catch (NoSuchAlgorithmException e) {
//            e.printStackTrace();
//        } catch (UnsupportedEncodingException e) {
//            e.printStackTrace();
//        }
//        return signature;
//    }
//
//    private static String byteToHex(final byte[] hash) {
//        Formatter formatter = new Formatter();
//        for (byte b : hash) {
//            formatter.format("%02x", b);
//        }
//        String result = formatter.toString();
//        formatter.close();
//        return result;
//    }
//
//
//    public static String SHA1(String str) {
//        try {
//            MessageDigest digest = MessageDigest
//                    .getInstance("SHA-1"); //如果是SHA加密只需要将"SHA-1"改成"SHA"即可
//            digest.update(str.getBytes());
//            byte messageDigest[] = digest.digest();
//            // Create Hex String
//            StringBuffer hexStr = new StringBuffer();
//            // 字节数组转换为 十六进制 数
//            for (int i = 0; i < messageDigest.length; i++) {
//                String shaHex = Integer.toHexString(messageDigest[i] & 0xFF);
//                if (shaHex.length() < 2) {
//                    hexStr.append(0);
//                }
//                hexStr.append(shaHex);
//            }
//            return hexStr.toString();
//
//        } catch (NoSuchAlgorithmException e) {
//            e.printStackTrace();
//        }
//        return null;
//    }

    @PostMapping("/shengcheng")
    public ApiResult<Boolean> unBinding(@RequestBody MjOrderCommon order) {
        //获取密钥逻辑------------------------
        //根据订单号查询订单明细表，然后将订单明细得信息生成密钥
        List<MjOrderDetail> list = mjOrderDetailService.list(new LambdaQueryWrapper<MjOrderDetail>().eq(MjOrderDetail::getOrderCode, order.getOrderCode()));
        //循环获取密钥
        if (list != null && list.size() > 0) {
            for (int i = 0; i < list.size(); i++) {
                MjOrderDetail mjOrderDetail = list.get(i);
                MojiMiYaoDto mojiMiYaoDto = new MojiMiYaoDto();
                mojiMiYaoDto.setOrderId(mjOrderDetail.getOrderMxCode());
                mojiMiYaoDto.setRegion(mjOrderDetail.getServiceCityCode());
                mojiMiYaoDto.setType(mjOrderDetail.getCallWayCode());
                mojiMiYaoDto.setRate(mjOrderDetail.getCallCountCode());
                mojiMiYaoDto.setDuration(mjOrderDetail.getServiceTimeCode());
                //判断支付时间，如果支付时间在生效时间之后，以支付时间为准，如果支付时间在生效时间之前，以生效时间为准
                SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
                // 使用format方法转换Date到指定格式的字符串
                String formattedDate = sdf.format(mjOrderDetail.getEffectTime());
                mojiMiYaoDto.setValidStartTime(formattedDate);
                List<String> endpoints = new ArrayList<>();
                if (!TextUtils.isEmpty(mjOrderDetail.getWeatherTypeCode())) {
                    String[] split = mjOrderDetail.getWeatherTypeCode().split("/");
                    for (int j = 0; j < split.length; j++) {
                        endpoints.add(split[j]);
                    }
                } else {
                    endpoints.add("GHC_CINFO");
                }
                mojiMiYaoDto.setEndpoints(endpoints);
                // 创建Gson对象
                Gson gson = new Gson();
                // 将对象转换为JSON字符串
                String jsonString = gson.toJson(mojiMiYaoDto);

                String s = null;
                try {
                    s = HttpUtils.sendPostRequest("/tob-data-misc/eshop/access/creation", jsonString);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                Gson gson1 = new Gson();
                MijiMoYaoVo1 mijiMoYaoVo1 = gson1.fromJson(s, MijiMoYaoVo1.class);
                if (mijiMoYaoVo1 != null && mijiMoYaoVo1.getCode() == 200) {
                    Gson gson2 = new Gson();
                    MijiMoYaoVo mijiMoYaoVo = gson2.fromJson(s, MijiMoYaoVo.class);
                    if (mijiMoYaoVo.getData().getAccess() != null && mijiMoYaoVo.getData().getAccess().getOrderId() != null) {
                        //核对订单号
                        if (mijiMoYaoVo.getData().getAccess().getOrderId().equals(mjOrderDetail.getOrderMxCode())) {
                            //将密钥更新到订单明细得springString2中
                            mjOrderDetail.setSpareString2(mijiMoYaoVo.getData().getAccess().getMdsPassword());
                            mjOrderDetail.setUpdateTime(new Date());
                            mjOrderDetail.setUseStatus(1);
                            mjOrderDetailService.updateById(mjOrderDetail);
                        }
                    }
                }
                else{
                    //获取墨迹密钥失败

                }


            }
        }
        //结束---------------------------
        return null;
    }

}

